<template>
  <div class="chat-container">
    <div class="status-bar">
      <span>{{ statusMessage }}</span>
      <button @click="requestRematch" v-if="isMatched">重新匹配</button>
    </div>
    <div class="message-list" ref="messageList">
      <div v-for="(msg, index) in messages" 
           :key="index" 
           :class="['message', msg.type, { 'self': msg.userName === userName }]">
        <div class="message-header" v-if="msg.type !== 'system'">
          <span class="sender">{{ msg.userName }}</span>
          <span class="message-time">{{ msg.time }}</span>
        </div>
        <div class="message-content" :class="{ 'system': msg.type === 'system' }">
          {{ msg.content }}
        </div>
      </div>
    </div>
    <div class="input-container">
      <input 
        v-model="inputMessage" 
        @keyup.enter="sendMessage"
        placeholder="输入消息按回车发送"
        type="text"
        :disabled="!isMatched"
      >
      <button @click="sendMessage" :disabled="!isMatched || !inputMessage.trim()">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed,onMounted ,onUnmounted  } from 'vue';

const ws = ref(null);
const messages = ref([]);
const inputMessage = ref('');
const messageList = ref(null);
const userId = ref(Date.now().toString(36) + Math.random().toString(36).substr(2));
const userName = ref(`用户${userId.value.substr(0, 6)}`);
const isMatched = ref(false);

const statusMessage = computed(() => {
  return isMatched.value ? '已连接' : '等待匹配中...';
});

// 初始化WebSocket连接
const initWebSocket = () => {
  ws.value = new WebSocket('ws://localhost:8080');

  ws.value.onopen = () => {
    // 发送连接消息
    ws.value.send(JSON.stringify({
      type: 'connect',
      userId: userId.value,
      userName: userName.value
    }));
  };

  ws.value.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      
      if (data.type === 'system') {
        addMessage('system', data.content);
        if (data.content.includes('匹配成功')) {
          isMatched.value = true;
        } else if (data.content.includes('断开连接') || data.content.includes('重新匹配')) {
          isMatched.value = false;
        }
      } else if (data.type === 'message') {
        addMessage('接收', data.content, data.userName);
      }
    } catch (error) {
      console.error('处理消息时出错:', error);
    }
  };

  ws.value.onclose = () => {
    isMatched.value = false;
    addMessage('system', '连接已断开');
  };

  ws.value.onerror = (error) => {
    console.error('WebSocket错误:', error);
    isMatched.value = false;
    addMessage('system', '连接出错');
  };
};

// 请求重新匹配
const requestRematch = () => {
  if (!ws.value) return;
  
  ws.value.send(JSON.stringify({
    type: 'rematch',
    userId: userId.value
  }));
  
  isMatched.value = false;
  addMessage('system', '正在重新匹配...');
};

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim() || !ws.value || !isMatched.value) return;

  const messageData = {
    type: 'chat',
    content: inputMessage.value,
    userId: userId.value,
    userName: userName.value
  };

  ws.value.send(JSON.stringify(messageData));
  addMessage('发送', inputMessage.value, userName.value);
  inputMessage.value = '';
};

// 添加消息到列表
const addMessage = (type, content, sender = null) => {
  messages.value.push({
    type,
    content,
    userName: sender,
    time: new Date().toLocaleTimeString()
  });
  
  setTimeout(() => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight;
    }
  }, 0);
};

// 组件挂载时初始化WebSocket
onMounted(() => {
  initWebSocket();
});

// 组件卸载时关闭WebSocket连接
onUnmounted(() => {
  if (ws.value) {
    ws.value.close();
  }
});
</script>

<style scoped>
/* 添加新的样式 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 10px;
}

.message.system .message-content {
  background-color: #fff3e0;
  text-align: center;
  padding: 8px;
  border-radius: 4px;
  margin: 10px auto;
  max-width: 80%;
  color: #666;
}

.input-container input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

button {
  padding: 8px 16px;
  background-color: #1976d2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

button:hover:not(:disabled) {
  background-color: #1565c0;
}
</style>